package com.oj.interceptor;

import com.oj.entity.User;
import com.oj.exception.OJException;
import com.oj.mapper.AttendMapper;
import com.oj.mapper.ContestMapper;
import com.oj.mapper.PrivilegeMapper;
import com.oj.service.ContestService;
import com.oj.service.UserService;
import com.oj.util.CodeMsg;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
public class ContestInterceptor implements HandlerInterceptor {
    @Autowired
    private UserService userService;

    @Autowired
    private PrivilegeMapper privilegeMapper;

    @Autowired
    private ContestService contestService;

    @Autowired
    private ContestMapper contestMapper;

    @Autowired
    private AttendMapper attendMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String url = request.getRequestURL().toString();
        Integer contestId = new Integer(0);
        Pattern pattern = Pattern.compile("\\b(/contest/)\\.?\\s*(\\d{1,4})\\b");
        Matcher matcher = pattern.matcher(url);
        while (matcher.find()) {
            String group = matcher.group();
            contestId = Integer.parseInt(group.replaceAll("\\D+", ""));
            break;
        }

        if (contestService.isContestEnded(contestId)) {
            return true;
        }

        User user = userService.getUserBySession(request);
        if (user == null) {
            response.sendRedirect(request.getContextPath() + "/enter");
            return false;
        }
        if (attendMapper.query(contestId, user.getUsername()) == null) {
            throw new OJException(CodeMsg.CONTEST_NEVER_REG);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
    }
}